package api

import (
	"github.com/gin-gonic/gin"
	"net/http"
)

type BaseController struct {
	ApiName string
}

type Result struct {
	Code int    `json:"code"`
	Msg  string `json:"msg"`
	Data any    `json:"data"`
}

// HandleResponseResult 处理有返回结果
func (c *BaseController) HandleResponseResult(ctx *gin.Context, err error, errMsg string, data any) {
	if err != nil {
		c.responseFail(ctx, err, errMsg)
	} else {
		c.responseSuccess(ctx, data)
	}
}

// HandleResponseNoResult 处理没有返回结果
func (c *BaseController) HandleResponseNoResult(ctx *gin.Context, err error, errMsg, msg string) {
	if err != nil {
		c.responseFail(ctx, err, errMsg)
	} else {
		c.Response(ctx, http.StatusOK, msg, nil)
	}
}

func (c *BaseController) responseFail(ctx *gin.Context, err error, msg string) {
	ctx.JSON(http.StatusInternalServerError, Result{
		Code: http.StatusInternalServerError,
		Msg:  msg + err.Error(),
	})
}

func (c *BaseController) responseSuccess(ctx *gin.Context, data any) {
	ctx.JSON(http.StatusOK, Result{
		Code: http.StatusOK,
		Msg:  "操作成功！",
		Data: data,
	})
}

func (c *BaseController) ResponseBadRequest(ctx *gin.Context) {
	c.Response(ctx, http.StatusBadRequest, "请求参数错误！", nil)
}

func (c *BaseController) Response(ctx *gin.Context, code int, msg string, data any) {
	ctx.JSON(code, Result{
		Code: code,
		Msg:  msg,
		Data: data,
	})
}

// BaseOperationController
// @Description: 增删改查操作
type BaseOperationController interface {
	// RegisterController
	// @Description: 注册Controller
	RegisterController(engine *gin.RouterGroup)

	Add(ctx *gin.Context)
	Remove(ctx *gin.Context)
	Modify(ctx *gin.Context)
	Find(ctx *gin.Context)
	FindById(ctx *gin.Context)
}
